<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '仅保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并出库',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !!data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
    {
      title: '部分出库',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !!!data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true, 1)
      },
    },
    {
      title: '全部出库',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !!!data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true, 0)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createPersonName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :data="data.productOrder" :produceTaskBillNo="route.query.produceTaskBillNo" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="outStockBillNo">
              <ElInputBox :data="form" dataName="outStockBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据状态" prop="outStockState">
              <ElSelectBox :data="form" dataName="outStockState" :options="options.state" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据类型" prop="outStockType">
              <ElSelectBox :data="form" dataName="outStockType" :options="options.type" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="申请单号" prop="associationBillNo" v-if="form.inStockType !== 'InStockType5'">
              <ElInputBox :data="form" dataName="associationBillNo" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据备注" prop="outStockBillRemark" class="wAuto">
              <ElInputBox :data="form" dataName="outStockBillRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="红冲原因" prop="redFlushReason" class="wAuto" v-if="!!form.redFlushReason">
              <ElInputBox :data="form" dataName="redFlushReason" type="textarea" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="作废原因" prop="disabledReason" class="wAuto" v-if="!!form.disabledReason">
              <ElInputBox :data="form" dataName="disabledReason" type="textarea" disabled />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <GoodList :data="{
            disabled: !isEdit,
            height: 490,
            rowKey: 'specificationCode',
            prop: 'detailList',
            tbody: form.detailList,
            thead: [
              {
                label: '申请数量',
                prop: 'requestQuantity',
                align: 'center',
                width: 100,
              },
              {
                label: '生产批次',
                prop: 'productionBatchNumber',
                align: 'center',
                width: 180,
              },
              {
                label: '生产日期',
                prop: 'productionDate',
                isRules: true,
                align: 'center',
                width: 120,
              },
              {
                label: '出库仓库',
                prop: 'areaShelfCode',
                formType: 'cascader',
                dataName: ['warehouseAreaCode', 'areaShelfCode'],
                options: options.warehouse,
                isRules: true,
                disabled: true,
                align: 'center',
                width: 200,
              },
              {
                label: '库存数量',
                prop: 'stockQuantity',
                align: 'center',
                width: 100,
              },
              {
                label: '出库数量',
                prop: 'outStockQuantity',
                formType: 'number',
                isRules: true,
                align: 'center',
                width: 160,
                changeBtn: (value: any, row: any) => {
                  if (value > row.stockQuantity) {
                    proxy.$message('出库数量不能大于库存数量', 'error');
                    row.outStockQuantity = row.stockQuantity
                  }
                },
              },
              {
                label: '备注',
                prop: 'outStockRemark',
                formType: 'textarea'
              },
            ],
            operation: [
              {
                label: '复制',
                icon: 'CopyDocument',
                click: (row: any, index: number) => {
                  if (!row.productionBatchCode) {
                    proxy.$message('请先选择出库批次', 'error');
                    return
                  }
                  let _notBatchCode: any = []
                  form.detailList.forEach((el: any) => {
                    if (el.stockGoodsCode) {
                      _notBatchCode.push(el.stockGoodsCode)
                    }
                  })
                  const _arr = JSON.parse(JSON.stringify(row.details)).filter((el: any) => {
                    return !_notBatchCode.includes(el.stockGoodsCode)
                  })
                  if (_arr.length > 0) {
                    const _newRow = _arr[0]
                    proxy.$message('复制成功');
                    //获取该物料出库总数量
                    const _total = form.detailList.reduce((sum: number, item: any) => {
                      if (item.stockGoodsCode === row.stockGoodsCode) {
                        return sum + item.outStockQuantity
                      } else {
                        return sum
                      }
                    }, 0);
                    //待出库数量
                    const _outboundNum = row.requestQuantity - _total
                    const _row = {
                      ...row,
                      productionBatchCode: _newRow.productionBatchCode,
                      productionBatchNumber: _newRow.productionBatchNumber,
                      productionDate: _newRow.productionDate,
                      warehouseAreaCode: _newRow.warehouseAreaCode,
                      areaShelfCode: _newRow.areaShelfCode,
                      stockGoodsCode: _newRow.stockGoodsCode,
                      stockQuantity: _newRow.stockQuantity,
                      outStockQuantity: Math.min(_outboundNum || 0, _newRow.stockQuantity || 0),
                    }
                    form.detailList.splice(index + 1, 0, _row)
                  } else {
                    proxy.$message('没有多余批次可出库', 'error');
                  }
                }
              },
              {
                label: '删除',
                icon: 'Delete',
              },
            ],
            addSelect: !!form.associationBillNo ? addSelect : null,
          }" @selectBtn="addMx">
          </GoodList>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { dataInfo, options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    outStockID: null, // 出库主键ID
    outStockBillNo: "", // 出库单据号（唯一识别码）
    outStockAction: 1, // 出库动作：1手动出库；2自动出库
    outStockType: "OutStockType6", // 出库类型代码
    getMaterialType: 0, // 领料类型
    outStockState: 1, // 出库单据状态：1待确认；2待出库；3已出库；4已红冲；5已作废
    associationBillNo: "", // 关联单据号
    receivePerson: "", // 申请人员代码
    receivePersonName: "", // 申请人员姓名
    outStockBillRemark: "", // 出库备注说明
    redFlushReason: "", // 红冲原因
    disabledReason: "", // 作废原因
    detailList: []
  },
});
const isEdit = ref(true)
const addSelect: any = reactive({
  title: '申请明细',
  rowKey: 'specificationCode',
  thead: [
    {
      label: '物料编号',
      prop: 'specificationCode',
      align: 'center',
      width: 120,
    },
    {
      label: '物料名称',
      prop: 'goodsName',
      align: 'left',
      width: null,
    },
    {
      label: '规格型号',
      prop: 'specificationName',
      align: 'center',
      width: 120,
    },
    {
      label: '类型',
      prop: 'goodsType',
      align: 'center',
      width: 120,
    },
    {
      label: '供应商',
      prop: 'supplierName',
      align: 'center',
      width: 260,
    },
    {
      label: '数量',
      prop: 'requestQuantity',
      align: 'center',
      width: 120,
    },
    {
      label: '单位',
      prop: 'goodsUnit',
      align: 'center',
      width: 120,
    },
  ],
  tbody: [],
})
//添加关联单明细
const addMx = (rows: any) => {
  const _rows = Array.isArray(rows) ? rows : [rows]
  let _arr = []
  if (!!data.form.associationBillNo) {
    //关联单入库
    _arr = _rows.map((el: any) => ({
      associationDetailNo: el.associationDetailNo, // 关联的申请单明细编码
      supplierCode: el.supplierCode, // 供应商编码
      goodsCode: el.goodsCode, // 物料编码
      specificationCode: el.specificationCode, // 规格编码
      requestQuantity: el.requestQuantity, // 申请数量
      productionBatchNumber: '', // 生产批次编码
      outStockQuantity: '', // 待出库数量
      outStockRemark: el.remark, // 申请数量
    }))
  } else {
    //其他入库
    _arr = _rows.map((el: any) => {
      const _productionBatch = el.details?.length > 0 ? el.details[0] : {}
      return {
        associationDetailNo: '', // 关联的申请单明细编码
        requestQuantity: 0, // 申请数量
        outStockQuantity: null, // 出库数量
        machineCode: '', // 出库数量
        goodsCode: el.goodsCode,// 物料编号
        supplierCode: el.supplierCode, // 供应商编码
        specificationCode: el.specificationCode, // 物料规格编码
        productionBatchCode: _productionBatch.productionBatchCode,//	生产批次编码
        productionBatchNumber: _productionBatch.productionBatchNumber,//	生产批次号
        productionDate: _productionBatch.productionDate ? proxy.$day(_productionBatch.productionDate) : '',//	生产日期
        warehouseAreaCode: _productionBatch.warehouseAreaCode,//	仓库分区代码
        areaShelfCode: _productionBatch.areaShelfCode,//	仓库分区代码
        stockGoodsCode: _productionBatch.stockGoodsCode,//	库存code
      }
    })
  }
  data.form.detailList.push(
    ..._arr
  )
}
//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    _getOrder(route.query)
    data.loading = false
    return
  }

  proxy.$api.OutStockBill.GetSingleOutStockBillView({
    queryBy: 0,
    queryValue: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = res
      _getOrder(res)
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });

  function _getOrder(row: any) {
    //判断关联单号是否存在
    if (!!!row.associationBillNo) return
    const requestTypeObj: any = {
      OutStockType2: 2,//采购退货
    }
    //获取关联单据明细
    proxy.$api.OutStockBill.GetOutStockRequestDetailViewList({
      requestType: requestTypeObj[row.outStockType || row.billType] || 1,//	申请单类型：1生产领料；2采购退货
      associationBillNo: row.associationBillNo,//申请单号
    })
      .then((res: any) => {
        addSelect.tbody = res
        //是否存在关联单号
        if (!!data.form.associationBillNo) return
        data.form.associationBillNo = row.associationBillNo
        data.form.outStockType = row.billType
        addMx(res)
      })
      .catch(() => {

      });
  }
};
const saveBtn = (form: any, isConfirm: boolean = false, isPartial?: number) => {
  const _form: any = {
    outStockAction: 1, // 出库动作：1手动出库；2自动出库
    outStockID: form.outStockID, // 出库动作：1手动出库；2自动出库
    outStockBillNo: form.outStockBillNo, //出库单号
    outStockState: form.outStockState, // 出库单号
    associationBillNo: form.associationBillNo, // 关联单号
    outStockType: form.outStockType, // 类型
    outStockBillRemark: form.outStockBillRemark, // 备注
    outStockBillMxList: form.detailList.map((el: any) => (
      {
        associationDetailNo: el.associationDetailNo, // 关联的申请单明细编码
        stockGoodsCode: el.stockGoodsCode, // 供应商编码
        supplierCode: el.supplierCode, // 供应商编码
        goodsCode: el.goodsCode, // 物料编码
        specificationCode: el.specificationCode, // 规格编码
        productionBatchCode: el.productionBatchCode, // 生产批次编码
        productionBatchNumber: el.productionBatchNumber, // 生产批次号
        productionDate: el.productionDate, // 生产日期
        warehouseAreaCode: el.warehouseAreaCode, // 仓库分区代码
        areaShelfCode: el.areaShelfCode, // 分区库位代码
        requestQuantity: el.requestQuantity, // 申请数量
        outStockQuantity: el.outStockQuantity, // 出库数量
        outStockRemark: el.outStockRemark, // 出库备注
      }
    ))
  }
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.OutStockBill.CreateOutStockBill(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState({
              outStockBillNo: res
            }, isPartial)
          } else {
            _sun()
          }
        })
        .catch(() => {
        });
      break;
    case '2'://编辑
      proxy.$api.OutStockBill.UpdateOutStockBill(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(_form, isPartial)
          } else {
            _sun()
          }
        })
        .catch(() => {
        });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
  function _setState(row: any, isPartial?: number) {
    setState(row, 3, '', isPartial)
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setState = (row: any, state: number = 1, reason: string = '', isPartial?: number) => {
  proxy.$api.OutStockBill.UpdateOutStockState({
    outStockBillNo: row.outStockBillNo,
    outStockState: state,//出库单据状态：1待确认；2待出库；3已出库；4已红冲；5已作废
    reason: reason,//原因
    isPartial: isPartial,//是否部分出库；0 完全出库，1 部分出库
  })
    .then((res: any) => {
      closeBtn('保存成功')
    })
    .catch(() => {
      closeBtn()
    });
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};

import { getOutStockType, getWarehouse } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  getOutStockType(options, 'type')//获取设备
  getWarehouse(options, 'warehouse')//获取仓库
});
</script>
